// Service Worker for Enhanced Notifications and PWA Support
const CACHE_NAME = 'aide-notification-v1';
const STATIC_CACHE = 'aide-static-v1';

// 缓存的静态资源
const STATIC_ASSETS = [
  '/',
  '/index.html',
  '/manifest.json',
  '/icon-192x192.png',
  '/icon-512x512.png'
];

// 安装 Service Worker
self.addEventListener('install', (event) => {
  console.log('Service Worker 安装中...');
  
  event.waitUntil(
    Promise.all([
      // 缓存静态资源
      caches.open(STATIC_CACHE).then((cache) => {
        console.log('缓存静态资源...');
        return cache.addAll(STATIC_ASSETS).catch(error => {
          console.warn('部分静态资源缓存失败:', error);
          // 继续执行，不阻止Service Worker安装
        });
      }),
      
      // 跳过等待，立即激活
      self.skipWaiting()
    ])
  );
});

// 激活 Service Worker
self.addEventListener('activate', (event) => {
  console.log('Service Worker 激活中...');
  
  event.waitUntil(
    Promise.all([
      // 清理旧缓存
      caches.keys().then((cacheNames) => {
        return Promise.all(
          cacheNames.map((cacheName) => {
            if (cacheName !== CACHE_NAME && cacheName !== STATIC_CACHE) {
              console.log('删除旧缓存:', cacheName);
              return caches.delete(cacheName);
            }
          })
        );
      }),
      
      // 立即控制所有客户端
      self.clients.claim()
    ])
  );
});

// 处理网络请求
self.addEventListener('fetch', (event) => {
  // 只处理同源请求
  if (!event.request.url.startsWith(self.location.origin)) {
    return;
  }

  // 对于导航请求，使用网络优先策略
  if (event.request.mode === 'navigate') {
    event.respondWith(
      fetch(event.request)
        .catch(() => caches.match('/index.html'))
    );
    return;
  }

  // 对于静态资源，使用缓存优先策略
  if (event.request.destination === 'image' || 
      event.request.destination === 'audio' ||
      event.request.url.includes('/static/')) {
    event.respondWith(
      caches.match(event.request)
        .then((response) => {
          if (response) {
            return response;
          }
          
          return fetch(event.request).then((response) => {
            // 缓存新的静态资源
            if (response.status === 200) {
              const responseClone = response.clone();
              caches.open(STATIC_CACHE).then((cache) => {
                cache.put(event.request, responseClone);
              });
            }
            return response;
          });
        })
    );
    return;
  }

  // 其他请求使用网络优先策略
  event.respondWith(
    fetch(event.request)
      .catch(() => {
        // 如果网络请求失败，尝试从缓存获取
        return caches.match(event.request);
      })
  );
});

// 处理推送通知
self.addEventListener('push', (event) => {
  console.log('收到推送消息:', event);
  
  let notificationData = {
    title: 'AIDE 提醒',
    body: '您有新的任务提醒',
    icon: '/icon-192x192.png',
    badge: '/icon-192x192.png',
    tag: 'aide-notification',
    requireInteraction: false,
    actions: [
      {
        action: 'view',
        title: '查看',
        icon: '/icons/view.png'
      },
      {
        action: 'dismiss',
        title: '忽略',
        icon: '/icons/dismiss.png'
      }
    ],
    data: {
      timestamp: Date.now(),
      url: '/'
    }
  };

  // 解析推送数据
  if (event.data) {
    try {
      const pushData = event.data.json();
      notificationData = { ...notificationData, ...pushData };
    } catch (error) {
      console.error('解析推送数据失败:', error);
      notificationData.body = event.data.text() || notificationData.body;
    }
  }

  // 显示通知
  event.waitUntil(
    self.registration.showNotification(notificationData.title, {
      body: notificationData.body,
      icon: notificationData.icon,
      badge: notificationData.badge,
      tag: notificationData.tag,
      requireInteraction: notificationData.requireInteraction,
      actions: notificationData.actions,
      data: notificationData.data,
      vibrate: [200, 100, 200],
      timestamp: notificationData.data?.timestamp || Date.now()
    })
  );
});

// 处理通知点击
self.addEventListener('notificationclick', (event) => {
  console.log('通知被点击:', event);
  
  const notification = event.notification;
  const action = event.action;
  const data = notification.data || {};

  // 关闭通知
  notification.close();

  // 处理不同的动作
  if (action === 'dismiss') {
    // 忽略通知，不做任何操作
    return;
  }

  // 确定要打开的URL
  let urlToOpen = data.url || '/';
  
  if (action === 'view' && data.taskId) {
    urlToOpen = `/#/task/${data.taskId}`;
  } else if (data.taskId) {
    urlToOpen = `/#/task/${data.taskId}`;
  }

  // 打开或聚焦到应用
  event.waitUntil(
    clients.matchAll({ type: 'window', includeUncontrolled: true })
      .then((clientList) => {
        // 查找已经打开的窗口
        for (const client of clientList) {
          if (client.url.includes(self.location.origin) && 'focus' in client) {
            // 如果找到已打开的窗口，聚焦并导航
            return client.focus().then(() => {
              if ('navigate' in client) {
                return client.navigate(urlToOpen);
              } else {
                return client.postMessage({
                  type: 'NAVIGATION',
                  url: urlToOpen
                });
              }
            });
          }
        }
        
        // 如果没有找到打开的窗口，打开新窗口
        if (clients.openWindow) {
          return clients.openWindow(urlToOpen);
        }
      })
  );
});

// 处理通知关闭
self.addEventListener('notificationclose', (event) => {
  console.log('通知被关闭:', event);
  
  // 可以在这里记录通知关闭的统计信息
  const notification = event.notification;
  const data = notification.data || {};
  
  // 向客户端发送通知关闭事件
  event.waitUntil(
    clients.matchAll().then((clientList) => {
      clientList.forEach((client) => {
        client.postMessage({
          type: 'NOTIFICATION_CLOSED',
          notificationTag: notification.tag,
          data: data
        });
      });
    })
  );
});

// 处理来自客户端的消息
self.addEventListener('message', (event) => {
  console.log('Service Worker 收到消息:', event.data);
  
  const { type, data } = event.data || {};
  
  switch (type) {
    case 'SKIP_WAITING':
      // 强制更新 Service Worker
      self.skipWaiting();
      break;
      
    case 'GET_VERSION':
      // 返回 Service Worker 版本
      event.ports[0]?.postMessage({
        type: 'VERSION',
        version: CACHE_NAME
      });
      break;
      
    case 'CLEAR_CACHE':
      // 清除缓存
      event.waitUntil(
        caches.keys().then((cacheNames) => {
          return Promise.all(
            cacheNames.map((cacheName) => caches.delete(cacheName))
          );
        }).then(() => {
          event.ports[0]?.postMessage({
            type: 'CACHE_CLEARED',
            success: true
          });
        })
      );
      break;
      
    case 'SCHEDULE_NOTIFICATION':
      // 安排延迟通知（简单实现，实际应该使用后端）
      if (data?.delay && data?.notification) {
        setTimeout(() => {
          self.registration.showNotification(
            data.notification.title,
            data.notification.options
          );
        }, data.delay);
      }
      break;
      
    case 'NOTIFICATION_ACTION':
      // 处理通知动作回调
      console.log('处理通知动作:', data);
      break;
      
    case 'CLIENT_ACTIVE':
      // 处理客户端活跃状态消息
      console.log('客户端已激活');
      break;
      
    default:
      console.log('未知消息类型:', type);
  }
});

// 处理同步事件（后台同步）
self.addEventListener('sync', (event) => {
  console.log('后台同步事件:', event);
  
  if (event.tag === 'background-sync') {
    event.waitUntil(
      // 执行后台同步任务
      doBackgroundSync()
    );
  }
});

// 后台同步函数
async function doBackgroundSync() {
  try {
    // 这里可以执行一些后台任务
    // 比如同步离线时的数据、检查待处理的通知等
    console.log('执行后台同步...');
    
    // 示例：检查是否有待发送的通知
    const cache = await caches.open(CACHE_NAME);
    const pendingNotifications = await cache.match('pending-notifications');
    
    if (pendingNotifications) {
      const notifications = await pendingNotifications.json();
      
      // 发送待处理的通知
      for (const notification of notifications) {
        if (notification.scheduledTime <= Date.now()) {
          await self.registration.showNotification(
            notification.title,
            notification.options
          );
        }
      }
      
      // 清除已发送的通知
      const remaining = notifications.filter(
        n => n.scheduledTime > Date.now()
      );
      
      if (remaining.length === 0) {
        await cache.delete('pending-notifications');
      } else {
        await cache.put('pending-notifications', 
          new Response(JSON.stringify(remaining))
        );
      }
    }
    
  } catch (error) {
    console.error('后台同步失败:', error);
  }
}

// 错误处理
self.addEventListener('error', (event) => {
  console.error('Service Worker 错误:', event);
});

self.addEventListener('unhandledrejection', (event) => {
  console.error('Service Worker 未处理的 Promise 拒绝:', event);
});

console.log('Service Worker 已加载');